//城市排序
export const sortCitiesByPinyin = (cities) => {
  return cities.sort((a, b) => a.py.localeCompare(b.py))
}

//根据城市名字，查询城市ID和拼音,并返回城市信息对象
export const getCityObjByName = (hotCityName, allCities) => {
  return allCities.find((city) => city.nm === hotCityName)
}

// 查询用户经纬度
export function getUserGeolocation () {
  return new Promise((resolve, reject) => {
    if ('geolocation' in navigator) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const { latitude, longitude } = position.coords
          resolve({ latitude, longitude })
        },
        (error) => {
          reject(new Error(`Error obtaining location: ${error.message}`))
        },
      )
    } else {
      reject(new Error('Geolocation is not supported by this browser.'))
    }
  })
}

// 获取当前日期
export const getCurrentDate = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
}

// 获取当前 年份
export const getCurrentYear = () => {
  const date = new Date()
  const year = date.getFullYear()
  return year.toString();
}
// 获取当前月份
export const getCurrentMonth = () => {
  const date = new Date()
  const month = date.getMonth() + 1
  return month.toString();
}

// 获取当前日期
export const getCurrentDay = () => {
  const date = new Date()
  const day = date.getDate()
  return day.toString();
}


// 检查是否还有下一页数据
// export const hasNextPage = (nextPageNum, offset, fetchFunction) => { }


//待映电影分组排序
export const adjustMovieData = (movies) => {
  // 创建一个空对象用于存储按日期分组的电影
  const groupedMovies = {};

  movies.forEach(movie => {
    // 提取上映日期和星期几
    const date = movie.rt;
    const comingTitle = movie.comingTitle; // 使用comingTitle替代dayOfWeek

    // 如果当前日期还没有在groupedMovies中出现，则初始化一个新的数组
    if (!groupedMovies[date]) {
      groupedMovies[date] = {
        date: date,
        comingTitle: comingTitle, // 使用comingTitle作为显示的日期标题
        movies: []
      };
    }

    // 根据showStateButton的内容确定按钮信息
    let buttonInfo = {};
    if (movie.showStateButton) {
      buttonInfo = {
        content: movie.showStateButton.content,
        color: movie.showStateButton.color,
        onlyPreShow: movie.showStateButton.onlyPreShow,
        shadowColor: movie.showStateButton.shadowColor
      };
    } else {
      buttonInfo = {
        content: "想看",
        color: "#FFB800"
      };
    }

    // 将电影信息添加到对应的日期下
    groupedMovies[date].movies.push({
      id: movie.id,
      haspromotionTag: movie.haspromotionTag,
      preShow: movie.preShow,
      globalReleased: movie.globalReleased,
      sc: movie.sc,
      nm: movie.nm,
      img: movie.img,
      star: movie.star,
      rt: movie.rt,
      wish: movie.wish,
      showst: movie.showst,
      wishst: movie.wishst,
      comingTitle: movie.comingTitle,
      showInfo: movie.showInfo || "",
      showStateButton: buttonInfo
    });
  });

  // 将结果转换为数组形式
  const groupedArray = Object.values(groupedMovies);

  // 分离具体日期和年份的数据
  const specificDateMovies = groupedArray.filter(group => group.date.includes('-'));
  const yearOnlyMovies = groupedArray.filter(group => !group.date.includes('-'));

  // 对具体日期的数据进行排序
  specificDateMovies.sort((a, b) => new Date(a.date) - new Date(b.date));

  // 对年份的数据进行排序
  yearOnlyMovies.sort((a, b) => a.date.localeCompare(b.date));

  // 合并具体日期和年份的数据
  return [...specificDateMovies, ...yearOnlyMovies]
}



// 格式化日期
// 使用示例
//const dates = ['2025-01-20', '2025-01-21', '2025-01-22', '2025-01-23', '2025-01-24'];
//const formattedDates = formatDates(dates);
//console.log(formattedDates);
export const formatDates = (dates) => {
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(today.getDate() + 1);
  const dayAfterTomorrow = new Date(today);
  dayAfterTomorrow.setDate(today.getDate() + 2);

  const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

  return dates.map(dateStr => {
    const date = new Date(dateStr);

    let formattedDate;
    if (date.toDateString() === today.toDateString()) {
      formattedDate = '今天';
    } else if (date.toDateString() === tomorrow.toDateString()) {
      formattedDate = '明天';
    } else if (date.toDateString() === dayAfterTomorrow.toDateString()) {
      formattedDate = '后天';
    } else {
      const dayOfWeek = daysOfWeek[date.getDay()];
      formattedDate = dayOfWeek;
    }

    const month = date.getMonth() + 1;
    const day = date.getDate();

    return `${formattedDate}${month}月${day}日`;
  });
}



// 电影散场
export const calculateEndTime = (startTime, duration) => {
  // 将开始时间分割成小时和分钟
  let [startHour, startMinute] = startTime.split(':').map(Number);

  // 计算总分钟数
  let totalMinutes = startHour * 60 + startMinute + duration;

  // 计算结束时间的小时和分钟
  let endHour = Math.floor(totalMinutes / 60);
  let endMinute = totalMinutes % 60;

  // 如果小时数超过24，则减去24（假设一天24小时制）
  if (endHour >= 24) {
    endHour -= 24;
  }

  // 格式化输出为两位数
  let endHourStr = endHour.toString().padStart(2, '0');
  let endMinuteStr = endMinute.toString().padStart(2, '0');

  return `${endHourStr}:${endMinuteStr}`;
}


/******* 电影详情页 ******/

// 格式化 包含 "imageMogr2" 图片URL
export const updateVideoGalleryImageUrl = (url) => {
  // 使用正则表达式匹配 imageMogr2 及其后面的所有查询参数
  return url.replace(/imageMogr2\/[^&]+/, 'imageView2/1/w/280/h/186/q/80');
}


export const updateActorImageUrl = (url) => {
  // 使用正则表达式匹配 imageMogr2 及其后面的所有查询参数
  return url.replace(/imageMogr2\/[^&]+/, 'imageView2/1/w/160/h/224/q/80');
}


export const updateMovieRelatedNewsImageUrl = (url) => {

  return url.replace(/300w_225h_1e_1c/, '220w_156h_80q_1e_1c');
}


export const updateMovieRelatedMoviesImageUrl = (url) => {
  // 使用正则表达式匹配 imageMogr2 及其后面的所有查询参数
  return url.replace(/imageMogr2\/[^&]+/, 'imageView2/1/w/192/h/268/q/80');
}

export const updateMoviePhotosImageUrl = (url) => {
  return url.replace(/imageMogr2\/[^&]+/, 'imageView2/1/w/140/h/140/q/80');
}


//将时间戳转化为年月日格式
export const timestampToDate = (timestamp) => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
}

// 根据经纬度查询两地距离
// 使用 Haversine 公式计算两地距离的
// lat1, lon1, lat2, lon2 分别是两地的经纬度
// 保留2位小数点 e.g: calculateDistance(39.9042, 116.4074, 31.2304, 121.4737).toFixed(2)
export const calculateDistance = (lat1, lon1, lat2, lon2) => {
  // 地球半径（千米）
  const R = 6371;

  // 将度数转换为弧度
  const dLat = toRadians(lat2 - lat1);
  const dLon = toRadians(lon2 - lon1);

  const radLat1 = toRadians(lat1);
  const radLat2 = toRadians(lat2);

  // Haversine公式
  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(radLat1) * Math.cos(radLat2) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  // 计算距离
  const distance = R * c;
  return distance.toFixed(1);
}
//经纬度转换为弧度
const toRadians = (degrees) => {
  return degrees * (Math.PI / 180);
}
